<script lang="ts" setup>
import type { DrawerModel, PurchaseProduction, PurchaseProductionStatus } from '@/index.d';
import {
  insertOne,
  urls,
  updateOne,
  physicalDeleteById,
  getListByConditions,
  useLoginUserStore
} from '@/index';
import type { FormInstance } from 'element-plus';
import { useRequest } from 'vue-request';

const drawerModel = defineModel<DrawerModel<PurchaseProduction>>('drawerModel', {
  required: true
});

const editable = ref(false);

const {
  data: getPurchasePartStatusListData,
  run: getPurchasePartStatusListRun,
  loading: getPurchasePartStatusListLoading
} = useRequest(() =>
  getListByConditions<PurchaseProductionStatus>(urls.purchaseProductionStatus, {
    purchaseProductionId: drawerModel.value.id
  })
);

const imageList = computed(() => {
  return (
    getPurchasePartStatusListData.value?.map(item => item.statusImageLink) as string[]
  ).reverse();
});

const title = computed(() => {
  const data = drawerModel.value.data;
  if (data) {
    return (
      '令号：' +
      data.productionReference +
      '，工件：' +
      data.partName +
      '（' +
      data.partReference +
      '）'
    );
  } else {
    return '获取数据错误';
  }
});

const productionStatusData = reactive<PurchaseProductionStatus>({
  id: 0,
  purchaseProductionId: drawerModel.value.id
});

const updateProductionStatus = (item: PurchaseProductionStatus) => {
  productionStatusData.id = item.id as number;
  productionStatusData.date = item.date;
  productionStatusData.description = item.description;
};
const deleteItem = async (item: PurchaseProductionStatus) => {
  await physicalDeleteById(urls.purchaseProductionStatus, item.id as number);
  getPurchasePartStatusListRun();
  reSetFormData();
};

const setFormData = async (res: PurchaseProductionStatus) => {
  productionStatusData.id = res.id;
  productionStatusData.purchaseProductionId = res.purchaseProductionId;
  productionStatusData.description = res.description;
  productionStatusData.statusImageUuid = res.statusImageUuid;
  productionStatusData.statusImageLink = res.statusImageLink;
  productionStatusData.date = res.date;
};

const reSetFormData = () => {
  productionStatusData.id = 0;
  delete productionStatusData.description;
  delete productionStatusData.statusImageUuid;
  delete productionStatusData.statusImageLink;
  delete productionStatusData.date;
};

const productionStatusDataFormRef = useTemplateRef<FormInstance>('productionStatusDataFormRef');
const saveFormData = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl
    .validate()
    .then(async valid => {
      if (valid) {
        if (productionStatusData.id === 0) {
          const res = (await insertOne<PurchaseProductionStatus>(
            urls.purchaseProductionStatus,
            productionStatusData
          )) as PurchaseProductionStatus;
          if (res) {
            setFormData(res);
            getPurchasePartStatusListRun();
          }
        } else {
          const tempFormData: PurchaseProductionStatus = {
            id: productionStatusData.id,
            description: productionStatusData.description,
            date: productionStatusData.date
          };

          const res = (await updateOne<PurchaseProductionStatus>(
            urls.purchaseProductionStatus,
            tempFormData
          )) as PurchaseProduction;

          if (res) {
            getPurchasePartStatusListRun();
          }
        }
      }
    })
    .catch(res => console.log(res));
};

watch(
  () => drawerModel.value.visible,
  value => {
    value && (productionStatusData.id = 0);
    !value && reSetFormData();
  },
  {
    immediate: true
  }
);

const productionStatusDataRules = {
  date: [{ required: true, message: '日期不能为空', trigger: 'blur' }],
  description: [{ required: true, message: '描述不能为空', trigger: 'blur' }]
};

const isLoginUser = computed(() => {
  return drawerModel.value.data?.creatorId === useLoginUserStore().loginUser.id;
});
</script>
<template>
  <el-drawer v-model="drawerModel.visible" destroy-on-close size="50%" :show-close="false">
    <template #title>
      <div class="title-container" style="display: flex; justify-content: space-between">
        <div class="title-container-title">{{ title }}</div>
        <div class="title-container-edit">
          <el-switch
            v-model="editable"
            active-text="可编辑"
            inactive-text="不可编辑"
            v-if="isLoginUser"
          />
        </div>
      </div>
    </template>
    <el-timeline v-loading="getPurchasePartStatusListLoading">
      <el-timeline-item
        placement="top"
        v-for="item in getPurchasePartStatusListData"
        :key="item.id"
        :timestamp="item.date + ' ' + item.description"
        type="success"
      >
        <el-button @click="updateProductionStatus(item)" type="primary" link v-if="editable">
          修改内容
        </el-button>
        <el-popconfirm title="确定删除吗？" @confirm="deleteItem(item)" v-if="editable">
          <template #reference>
            <el-button type="danger" link>删除节点</el-button>
          </template>
        </el-popconfirm>
        <div class="image-container-image">
          <HqUploadOneImagePurchase
            :key-word="item.statusImageUuid!"
            :editable="editable"
            :image-list="imageList"
          />
        </div>
      </el-timeline-item>
    </el-timeline>
    <template #footer v-if="editable">
      <el-form
        :model="productionStatusData"
        ref="productionStatusDataFormRef"
        :rules="productionStatusDataRules"
      >
        <el-row :gutter="20">
          <el-col :span="12" v-show="false">
            <el-form-item label="id" prop="id">
              <el-input v-model="productionStatusData.id" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="false">
            <el-form-item label="purchaseProductionId" prop="purchaseProductionId">
              <el-input v-model="productionStatusData.purchaseProductionId" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="日期" prop="date" style="width: 100%">
              <el-date-picker
                v-model="productionStatusData.date"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="描述" prop="description">
              <el-input v-model.trim="productionStatusData.description" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-button
              type="primary"
              style="width: 100%"
              @click="saveFormData(productionStatusDataFormRef!)"
            >
              <span v-if="productionStatusData.id === 0">新增 </span>
              <span v-else>修改</span>
            </el-button>
          </el-col>
          <el-col :span="12">
            <el-button
              type="warning"
              style="width: 100%"
              @click="reSetFormData"
              v-if="productionStatusData.id !== 0"
            >
              增加新数据需先点击此处清空
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </template>
  </el-drawer>
</template>
<style lang="scss" scoped>
.image-container {
  .image-container-button {
    height: 40px;
    line-height: 40px;
    display: flex;
    align-items: baseline;
    * {
      margin: 0 5px;
    }
  }
}
</style>
